#!/usr/bin/env node

const fs = require('fs'),
            path = require('path');
      join = require('path').join,
            pathName = 'sysFile',
                  file    = process.argv[3],
                        command = process.argv[2],
                              fileList = [];

if (command == '-list') {
  function readdir(path) {
        var files = fs.readdirSync(path);
        for (var i = 0; i < files.length; i++) {
                var ddd=join(path,files[i]);
                if (fs.statSync(ddd).isFile()) {
                          var obj = new Object();
                                  obj.name = ddd;
                                          obj.size = fs.statSync(ddd).size;
                                                  fileList.push(obj);
                                                        
                }
                else if (fs.statSync(ddd).isDirectory()) {
                          readdir(ddd);
                                
                }
                    
        }
          
  }
    readdir(pathName);
      var objtemp = new Object();
      for (var i = 0; i < fileList.length; i++) {
        for (var j = 0; j < fileList.length; j++) {
          if (fileList[i].size < fileList[j].size) {
                    objtemp = fileList[i];
                            fileList[i] = fileList[j];
                                    fileList[j] = objtemp;
                                          
          }
              
        }
          
      }
      for (var i = 0; i < fileList.length; i++) {
            fileList[i].name = path.basename(fileList[i].name);
                console.log(JSON.stringify(fileList[i]));
                  
      }

}

else if (command == '-show') {
    var filepath = join(pathName, file);
    try {
            console.log(fs.readFileSync(filepath).toString('utf8'));

              
    } catch (err) {
            console.log('该文件不存在');
              
    }

}

else if (command == '-del') {
    var filepath = join(pathName, file);
    if (fs.statSync(filepath).isFile()) {
            fs.unlinkSync(filepath);
                  console.log(file + '删除成功');
                    
    }
    else if (fs.statSync(filepath).isDirectory()) {
            deleteDir(filepath);
                  console.log(file + '删除成功');
                    
    }
    function deleteDir(folder) {
          var files = fs.readdirSync(folder);
          for(var i=0; i<files.length; i++) {
                  var file = join(folder, files[i]);

                  if(fs.statSync(file).isFile()) {
                            fs.unlinkSync(file);
                                    continue;
                                          
                  }
                        if(fs.statSync(file).isDirectory()) deleteDir(file);
                            
          }
              fs.rmdirSync(folder);
                
    } 

}


